package one.coder.netty.chapter.eight;

import one.coder.netty.chapter.common.model.Command;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

/**
 * 对象传递，客户端代码
 * 
 * @author lihzh
 * @alia OneCoder
 * @blog http://www.coderli.com
 */
public class ObjectClientHandler extends SimpleChannelHandler {

	private static int excount = 0;

	/**
	 * 当绑定到服务端的时候触发，给服务端发消息。
	 * 
	 * @author lihzh
	 * @alia OneCoder
	 */
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		// 向服务端发送Object信息
		sendObject(e.getChannel());
	}

	/**
	 * 发送Object
	 * 
	 * @param channel
	 * @author lihzh
	 * @alia OneCoder
	 */
	private void sendObject(final Channel channel) {
		loopSend(channel);
//		new Thread(new Runnable() {
//
//			@Override
//			public void run() {
//				long start = System.currentTimeMillis();
//				Command command = new Command();
//				command.setActionName("Hello action.");
//				channel.write(command);
//				long end = System.currentTimeMillis();
//				System.out.println("Cost time: " + (end - start));
//
//			}
//		}).start();
		
	}

	private void loopSend(Channel channel) {
		for (int i = 0; i < 10; i++) {
			long start = System.currentTimeMillis();
			Command command = new Command();
			command.setActionName("Hello action.");
			channel.write(command);
			long end = System.currentTimeMillis();
			System.out.println("[1]: " + (end - start));
		}
	}

	/**
	 * 
	 */
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		excount++;
		System.out.println("Exception: " + excount + e.getCause());
		e.getCause().printStackTrace();
	}

}
